package com.martinwj.camera2demo.ui;

import android.content.Context;
import android.util.AttributeSet;
import android.view.TextureView;

/**
 * author: wj
 * created on: 2021/5/28 13:54
 * description: 用于相机预览，可以将其调整为指定的宽高比
 */
public class AutoFitTextureView extends TextureView {

    private int mRatioWidth = 0;
    private int mRatioHeight = 0;

    public AutoFitTextureView(Context context) {
        this(context, null);
    }

    public AutoFitTextureView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AutoFitTextureView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    /**
     * 设置此视图的纵横比。视图的大小将根据从参数计算出的比率进行测量。请注意，参数的实际大小无关紧要，
     * 也就是说，调用setAspectRatio（2，3）和setAspectRatio（4，6）会得到相同的结果。
     *
     * @param width 相对水平尺寸
     * @param height 相对垂直尺寸
     */
    public void setAspectRatio(int width, int height) {
        if (width < 0 || height < 0) {
            // 大小不能为负数。
            throw new IllegalArgumentException("宽高大小不能为负数。");
        }
        mRatioWidth = width;
        mRatioHeight = height;
        requestLayout();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        if (0 == mRatioWidth || 0 == mRatioHeight) {
            setMeasuredDimension(width, height);
        } else {
            if (width < height * mRatioWidth / mRatioHeight) {
                setMeasuredDimension(width, width * mRatioHeight / mRatioWidth);
            } else {
                setMeasuredDimension(height * mRatioWidth / mRatioHeight, height);
            }
        }
    }
}
